// API调用示例 - 精简版用户系统

const API_BASE = 'http://localhost:3001/api';

// 1. 用户注册
async function register(username, password) {
    try {
        const response = await fetch(`${API_BASE}/auth/register`, {
            method: 'POST',
            headers: {
                'Content-Type': 'application/json',
            },
            body: JSON.stringify({
                username: username,
                password: password
            })
        });

        const result = await response.json();
        console.log('注册结果:', result);
        return result;
    } catch (error) {
        console.error('注册失败:', error);
        return { success: false, message: '网络错误' };
    }
}

// 2. 用户登录
async function login(username, password) {
    try {
        const response = await fetch(`${API_BASE}/auth/login`, {
            method: 'POST',
            headers: {
                'Content-Type': 'application/json',
            },
            body: JSON.stringify({
                username: username,
                password: password
            })
        });

        const result = await response.json();
        
        if (result.success && result.data && result.data.token) {
            // 保存token
            localStorage.setItem('authToken', result.data.token);
            console.log('登录成功，token已保存');
        }
        
        console.log('登录结果:', result);
        return result;
    } catch (error) {
        console.error('登录失败:', error);
        return { success: false, message: '网络错误' };
    }
}

// 3. 获取用户信息
async function getProfile() {
    const token = localStorage.getItem('authToken');
    
    if (!token) {
        console.log('未找到认证token，请先登录');
        return { success: false, message: '请先登录' };
    }

    try {
        const response = await fetch(`${API_BASE}/auth/profile`, {
            method: 'GET',
            headers: {
                'Authorization': `Bearer ${token}`,
                'Content-Type': 'application/json',
            }
        });

        const result = await response.json();
        console.log('用户信息:', result);
        return result;
    } catch (error) {
        console.error('获取用户信息失败:', error);
        return { success: false, message: '网络错误' };
    }
}

// 使用示例：
// register('testuser', 'password123');
// login('testuser', 'password123');
// getProfile(); 